package org.lingshi.security;


import org.lingshi.entity.Permission;
import org.lingshi.entity.Role;
import org.lingshi.entity.SysUser;
import org.lingshi.service.impl.PermissionService;
import org.lingshi.service.impl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser dbUser = userService.getUserByName(username);
        if (dbUser == null){
            throw new UsernameNotFoundException("该用户不存在");
        }
        Role role = dbUser.getPrimaryRole();
        Set<Permission> perms = permissionService.getPermissionByRole(role.getId());
        Set<GrantedAuthority> authcSet = new HashSet<>();
        authcSet.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        perms.forEach(
                (x)->{authcSet.add(new SimpleGrantedAuthority(x.getPermName()));});
        return new UserSecurity(dbUser,authcSet);
    }
}
